package tcpserver.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tcpserver.service.TcpServerService;

import java.util.HashMap;
import java.util.Map;

/**
 * TCP服务器管理控制器
 * 
 * 提供TCP服务器的监控、管理和控制的REST API
 */
@RestController
@RequestMapping("/api/tcp-server")
@CrossOrigin(origins = "*")
public class TcpServerController {
    
    private static final Logger logger = LoggerFactory.getLogger(TcpServerController.class);
    
    @Autowired
    private TcpServerService tcpServerService;
    
    /**
     * 获取服务器状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getServerStatus() {
        try {
            Map<String, Object> status = tcpServerService.getServerStatus();
            return ResponseEntity.ok(createSuccessResponse("获取服务器状态成功", status));
        } catch (Exception e) {
            logger.error("获取服务器状态失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("获取服务器状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取服务器配置
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getServerConfig() {
        try {
            Map<String, Object> config = tcpServerService.getServerConfig();
            return ResponseEntity.ok(createSuccessResponse("获取服务器配置成功", config));
        } catch (Exception e) {
            logger.error("获取服务器配置失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("获取服务器配置失败: " + e.getMessage()));
        }
    }
    
    /**
     * 重启服务器
     */
    @PostMapping("/restart")
    public ResponseEntity<Map<String, Object>> restartServer() {
        try {
            boolean success = tcpServerService.restartServer();
            if (success) {
                return ResponseEntity.ok(createSuccessResponse("服务器重启成功", null));
            } else {
                return ResponseEntity.internalServerError()
                        .body(createErrorResponse("服务器重启失败"));
            }
        } catch (Exception e) {
            logger.error("重启服务器失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("重启服务器失败: " + e.getMessage()));
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        try {
            Map<String, Object> health = tcpServerService.getHealthCheck();
            return ResponseEntity.ok(health);
        } catch (Exception e) {
            logger.error("健康检查失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("健康检查失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取服务器统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> stats = tcpServerService.getServerStatistics();
            return ResponseEntity.ok(createSuccessResponse("获取统计信息成功", stats));
        } catch (Exception e) {
            logger.error("获取统计信息失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("获取统计信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 发送广播消息
     */
    @PostMapping("/broadcast")
    public ResponseEntity<Map<String, Object>> broadcastMessage(@RequestBody Map<String, String> request) {
        try {
            String message = request.get("message");
            if (message == null || message.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(createErrorResponse("消息内容不能为空"));
            }
            
            boolean success = tcpServerService.broadcastMessage(message);
            if (success) {
                return ResponseEntity.ok(createSuccessResponse("广播消息发送成功", null));
            } else {
                return ResponseEntity.internalServerError()
                        .body(createErrorResponse("广播消息发送失败"));
            }
        } catch (Exception e) {
            logger.error("发送广播消息失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("发送广播消息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取服务器信息概览
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getServerInfo() {
        try {
            Map<String, Object> info = new HashMap<>();
            info.put("name", "RTU TCP Server");
            info.put("version", "1.0.0");
            info.put("description", "基于Netty的高性能TCP服务器");
            info.put("author", "RTU Team");
            info.put("framework", "Spring Boot + Netty");
            
            // 合并状态和统计信息
            info.putAll(tcpServerService.getServerStatus());
            
            return ResponseEntity.ok(createSuccessResponse("获取服务器信息成功", info));
        } catch (Exception e) {
            logger.error("获取服务器信息失败", e);
            return ResponseEntity.internalServerError()
                    .body(createErrorResponse("获取服务器信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        if (data != null) {
            response.put("data", data);
        }
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}